<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*
* LISTCOMMON class - common functions for listing, searching, selecting etc. resources
* 
* @author Mark Grimshaw
* @version 1
* $Header: /cvsroot/wikindx/wikindx3/core/list/LISTCOMMON.php,v 1.36 2007/10/21 12:01:56 sirfragalot Exp $
*/
class LISTCOMMON
{
// Constructor
	function LISTCOMMON($db, $vars = FALSE)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/user/USER.php");
		$this->user = new USER($this->db);
	}
/**
* pagingStyle() -- return SQL statement and paging object if paging is alphabetic
*
*/
	function pagingStyle($sqlTotal, $order, $where)
	{
// write un-paged statement to session in case we need to export to RTF etc.
		$this->session->setVar('sql_stmt', addslashes($sqlTotal));
		if(($this->session->getVar('setup_pagingStyle') == 'A') && 
			(($order == 'title') || ($order == 'creator')|| ($order == 'institution')))
			//(($order == 'title') || ($order == 'creator')))
		{
			include_once("core/paging/PAGINGALPHA.php");
			$paging = new PAGINGALPHA($this->db, $this->vars, $sqlTotal);
			$sqlTotal = $paging->getPaging($sqlTotal, $order, $where);
			return array($sqlTotal, $paging);
		}
		else
			return array($sqlTotal, FALSE);
	}
/**
* userBibCondition() - return a SQL condition clause if we are browsing a user bibliography to ensure that 
* listed, selected or searched resources come only from that user bibliography. If we are browsing the 
* master WIKINDX bibliography, return FALSE
*
* @return	SQL condition clasue or FALSE
*/
	function userBibCondition()
	{
		$condition = FALSE;
		if($useBib = $this->session->getVar("mywikindx_bibliography_use"))
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('bibliography'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($useBib));
			$dbBibs = $this->db->fetchOne($recordset);
			$bibsArray = explode(",", $dbBibs);
			foreach($bibsArray as $resourceId)
				$conditionArray[] = $this->db->tidyInput($resourceId);
			$condition .= " (WKX_resource.id = " . implode(" OR WKX_resource.id = ", $conditionArray) . ")";
		}
		return $condition;
	}
/*
* listResources() - list each resource in the query in tabular format with view and edit links as required.
* 
* @author Mark Grimshaw
* 
* @param string $sqlTotal - SQL select statement to grab all resources required.
* @param string $queryString - URL query string such as "action=listProcess"
* @param string $listTYpe - What type of list/search/select process is this being called from?
* @param array $patterns - optional array of search terms to be matched and highlighted in bibstyle->process()
* @param string $message - optional message printed first
* @return string $pString
*/
	function listResources($sqlTotal, $queryString, $listType, $patterns = FALSE, $message = FALSE, $paging = FALSE)
	{
/**
* If this is a new type of list process, reset the paging counter
*/
		if(($this->session->getVar('sql_lastMulti') != $listType) || 
			$this->session->getVar('bookmark_multiView'))
		{
			$this->session->delVar('mywikindx_pagingStart');
			$this->session->delVar('mywikindx_pagingStartAlpha');
		}
		$this->session->delVar('sql_front'); // stop sending users back to front page after edit etc. operations
// Displaying only attachments?
		if($this->session->getVar($listType . '_displayAttachment'))
		{
			list($pString, $pagingString) = $this->listAttachments($sqlTotal, $queryString, $listType, $patterns, $message);
			return array($pString, $pagingString);
		}
// Turn on the 'add bookmark' menu item
		$this->session->setVar("bookmark_displayAdd", TRUE);
		include_once("core/icons/LOADICONS.php");
		$icons = new LOADICONS();
		include_once("core/statistics/STATISTICS.php");
		$stats = new STATISTICS($this->db, FALSE);
		include_once("core/file/export/COINS.php");
		$coins = new COINS($this->db);
		if(!$paging) // numeric
		{
			include_once("core/paging/PAGING.php");
			$paging = new PAGING($this->db, $this->vars, $sqlTotal);
// Create SQL statement limiting no. resources to display based on paging preferences.
			$recordset = $paging->sqlLimit($sqlTotal);
		}
		else	// alphabetic
		{
			$paging->listType = $listType;
			$recordset = $this->db->query($sqlTotal);
		}
		include_once("core/html/TABLE.php");
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "html");
		$bibStyle->bibformat->patterns = $patterns;
		include_once("core/html/FORM.php");
		include("config.php");
		$pString = $message ? $message : '';
// type of CSS class required.
		$icons->getIconInfo('view');
		$icons->getIconInfo('viewmeta');
		$icons->getIconInfo('edit');
		$icons->getIconInfo('delete');
		$icons->getIconInfo('bibtex');
		$viewLink = $icons->viewExists ? "imgLink" : "link";
		$editLink = $icons->editExists ? "imgLink" : "link";
		$deleteLink = $icons->editExists ? "imgLink" : "link";
		$bibtexLink = $icons->bibtexExists ? "imgLink" : "link";
		$superadmin = $this->session->getVar('setup_superadmin');
		$write = $this->session->getVar('setup_write');
		$multiUser = $this->session->getVar("setup_multiUser");
		$userId = $this->session->getVar('setup_userId');
// write statement to session in case we need to export to RTF etc.
//		$this->session->setVar('sql_stmt', addslashes($sqlTotal));
		$this->session->setVar("sql_lastView", 'multi');
// Display selection of user bibliographies if existing.
		list($string, $form) = $this->displaySelect($paging, $listType);
		$pString .= $string;
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$index = 0;
		$highlight = $patterns ? htmlentities("&search=highlight") : FALSE;
		$stats->getMaxAccesses();
		while($row = $this->db->loopRecordSet($recordset))
		{
			$links = array();
			if($multiUser)
			{
				$userAddEdit = $this->user->displayUserAddEdit($row['addUserIdResource'], $row['editUserIdResource']);
// tidy up $userAddEdit
				$userArray = explode("&nbsp;&nbsp;&nbsp;", $userAddEdit);
				if(array_key_exists(1, $userArray))
					$links[] = trim(preg_replace("/&nbsp;+/", ' ', $userArray[1]));
				else
					$links[] = str_replace("<br />", '', $userArray[0]);
			}
// display CMS link if required
// link is actually a JavaScript call
			if($this->session->getVar('setup_displayCmsLink'))
				$links[] = MISC::a('cmsLink', "CMS:&nbsp;" . $row['resourceId'], 
					"javascript:openCmsWindow('index.php?action=cmsDisplay" . "&amp;id=" . $row['resourceId'] . "')");
// display bibtex link
// link is actually a JavaScript call
			if($this->session->getVar('setup_displayBibtexLink'))
				$links[] = "&nbsp;" . MISC::a($bibtexLink, $icons->bibtex, 
				"javascript:openBibtexWindow('index.php?action=bibtexDisplay" . "&amp;id=" . $row['resourceId'] . "')");
			$view = ($row['quotes'] || $row['paraphrases'] || $row['musings']) ? 
				$icons->viewmeta : $icons->view;
			$links[] = MISC::a("$viewLink", $view, "index.php?action=resourceView" . 
				htmlentities("&id=" . $row['resourceId'] . "&access=1") . $highlight);
			$edit = FALSE;
			if($write && !$WIKINDX_ORIGINATOR_EDITONLY)
			{
				$links[] = MISC::a("$editLink", $icons->edit, 
					"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$edit = TRUE;
			}
			else if($write && ($row['addUserIdResource'] == $userId))
			{
				$links[] = MISC::a("$editLink", $icons->edit, 
					"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$edit = TRUE;
			}
			if($superadmin)
			{
				if(!$edit)
					$links[] = MISC::a("$editLink", $icons->edit, 
						"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$links[] = MISC::a($deleteLink, $icons->delete, "index.php?action=deleteResourceConfirm" . 
					htmlentities("&resource_id=" . $row['resourceId']));
			}
			if($multiUser)
			{
				$popularityIndex = "&nbsp;" . $this->messages->text("misc", "popIndex") . "&nbsp;" . 
					$stats->getPopularityIndex($row['accesses']) . "%";
				$maturityIndex = $row['maturityIndex'] ? "&nbsp;" . 
					$this->messages->text("misc", "matIndex") . "&nbsp;" . 
					$row['maturityIndex'] . "/10" . MISC::br()
					:
					FALSE;
			}
			if($form)
				$checkBox = "&nbsp;" . FORM::checkBox(FALSE, "bib_" . $row['resourceId']);
			else
				$checkBox = FALSE;
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= TABLE::trStart();
// write Coins <span> data
			$coinsString = $coins->coinsDisplay($row);
			$pString .= TABLE::td($coinsString . $bibStyle->process($row), $class);
			foreach($links as $link)
				$pString .= TABLE::td($link . "&nbsp;", $class, "right", "top");
			if($multiUser)
				$pString .= TABLE::td(MISC::span($maturityIndex . $popularityIndex, 'hint'), 
					$class, "right", "top");
			$pString .= TABLE::td($checkBox, $class, "right", "top");
			$pString .= TABLE::trEnd();
			$index++;
		}
		$pString .= TABLE::tableEnd();
		if($form)
			$pString .= FORM::formEnd();
		$pagingString = $paging->links($queryString);
// set the lastMulti session variable for quick return to this process.
		$this->session->setVar('sql_lastMulti', $listType);
		return array($pString, $pagingString);
	}
		
	/*
* listCreator() - list each resource in the query in tabular format with view and edit links as required.
* 
* @author Mark Grimshaw
* 
* @param string $sqlTotal - SQL select statement to grab all resources required.
* @param string $queryString - URL query string such as "action=listProcess"
* @param string $listTYpe - What type of list/search/select process is this being called from?
* @param array $patterns - optional array of search terms to be matched and highlighted in bibstyle->process()
* @param string $message - optional message printed first
* @return string $pString
*/
	function listCreator($sqlTotal, $queryString, $listType, $patterns = FALSE, $message = FALSE, $paging = FALSE)
	{
/**
* If this is a new type of list process, reset the paging counter
*/
		if(($this->session->getVar('sql_lastMulti') != $listType) || 
			$this->session->getVar('bookmark_multiView'))
		{
			$this->session->delVar('mywikindx_pagingStart');
			$this->session->delVar('mywikindx_pagingStartAlpha');
		}
		$this->session->delVar('sql_front'); // stop sending users back to front page after edit etc. operations
// Displaying only attachments?
		if($this->session->getVar($listType . '_displayAttachment'))
		{
			list($pString, $pagingString) = $this->listAttachments($sqlTotal, $queryString, $listType, $patterns, $message);
			return array($pString, $pagingString);
		}
// Turn on the 'add bookmark' menu item
		$this->session->setVar("bookmark_displayAdd", TRUE);
		include_once("core/icons/LOADICONS.php");
		$icons = new LOADICONS();
		include_once("core/statistics/STATISTICS.php");
		$stats = new STATISTICS($this->db, FALSE);
		include_once("core/file/export/COINS.php");
		$coins = new COINS($this->db);
		if(!$paging) // numeric
		{
			include_once("core/paging/PAGING.php");
			$paging = new PAGING($this->db, $this->vars, $sqlTotal);
// Create SQL statement limiting no. resources to display based on paging preferences.
			$recordset = $paging->sqlLimit($sqlTotal);
		}
		else	// alphabetic
		{
			$paging->listType = $listType;
			$recordset = $this->db->query($sqlTotal);
		}
		include_once("core/html/TABLE.php");
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($this->db, "html");
		$bibStyle->bibformat->patterns = $patterns;
		include_once("core/html/FORM.php");
		include("config.php");
		$pString = $message ? $message : '';
// type of CSS class required.
		$icons->getIconInfo('view');
		$icons->getIconInfo('viewmeta');
		$icons->getIconInfo('edit');
		$icons->getIconInfo('delete');
		$icons->getIconInfo('bibtex');
		$viewLink = $icons->viewExists ? "imgLink" : "link";
		$editLink = $icons->editExists ? "imgLink" : "link";
		$deleteLink = $icons->editExists ? "imgLink" : "link";
		$bibtexLink = $icons->bibtexExists ? "imgLink" : "link";
		$superadmin = $this->session->getVar('setup_superadmin');
		$write = $this->session->getVar('setup_write');
		$multiUser = $this->session->getVar("setup_multiUser");
		$userId = $this->session->getVar('setup_userId');
// write statement to session in case we need to export to RTF etc.
//		$this->session->setVar('sql_stmt', addslashes($sqlTotal));
		$this->session->setVar("sql_lastView", 'multi');
// Display selection of user bibliographies if existing.
		list($string, $form) = $this->displaySelect($paging, $listType);
		$pString .= $string;
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "center");
		$index = 0;
		$highlight = $patterns ? htmlentities("&search=highlight") : FALSE;
		$stats->getMaxAccesses();
		while($row = $this->db->loopRecordSet($recordset))
		{
			$links = array();
			if($multiUser)
			{
				$userAddEdit = $this->user->displayUserAddEdit($row['addUserIdResource'], $row['editUserIdResource']);
// tidy up $userAddEdit
				$userArray = explode("&nbsp;&nbsp;&nbsp;", $userAddEdit);
				if(array_key_exists(1, $userArray))
					$links[] = trim(preg_replace("/&nbsp;+/", ' ', $userArray[1]));
				else
					$links[] = str_replace("<br />", '', $userArray[0]);
			}
// display CMS link if required
// link is actually a JavaScript call
			if($this->session->getVar('setup_displayCmsLink'))
				$links[] = MISC::a('cmsLink', "CMS:&nbsp;" . $row['resourceId'], 
					"javascript:openCmsWindow('index.php?action=cmsDisplay" . "&amp;id=" . $row['resourceId'] . "')");
// display bibtex link
// link is actually a JavaScript call
			if($this->session->getVar('setup_displayBibtexLink'))
				$links[] = "&nbsp;" . MISC::a($bibtexLink, $icons->bibtex, 
				"javascript:openBibtexWindow('index.php?action=bibtexDisplay" . "&amp;id=" . $row['resourceId'] . "')");
			$view = ($row['quotes'] || $row['paraphrases'] || $row['musings']) ? 
				$icons->viewmeta : $icons->view;
			$links[] = MISC::a("$viewLink", $view, "index.php?action=resourceView" . 
				htmlentities("&id=" . $row['resourceId'] . "&access=1") . $highlight);
			$edit = FALSE;
			if($write && !$WIKINDX_ORIGINATOR_EDITONLY)
			{
				$links[] = MISC::a("$editLink", $icons->edit, 
					"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$edit = TRUE;
			}
			else if($write && ($row['addUserIdResource'] == $userId))
			{
				$links[] = MISC::a("$editLink", $icons->edit, 
					"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$edit = TRUE;
			}
			if($superadmin)
			{
				if(!$edit)
					$links[] = MISC::a("$editLink", $icons->edit, 
						"index.php?action=resourceEdit" . htmlentities("&id=" . $row['resourceId']));
				$links[] = MISC::a($deleteLink, $icons->delete, "index.php?action=deleteResourceConfirm" . 
					htmlentities("&resource_id=" . $row['resourceId']));
			}
			if($multiUser)
			{
				$popularityIndex = "&nbsp;" . $this->messages->text("misc", "popIndex") . "&nbsp;" . 
					$stats->getPopularityIndex($row['accesses']) . "%";
				$maturityIndex = $row['maturityIndex'] ? "&nbsp;" . 
					$this->messages->text("misc", "matIndex") . "&nbsp;" . 
					$row['maturityIndex'] . "/10" . MISC::br()
					:
					FALSE;
			}
			if($form)
				$checkBox = "&nbsp;" . FORM::checkBox(FALSE, "bib_" . $row['resourceId']);
			else
				$checkBox = FALSE;
			$class = $index % 2 ? 'alternate2' : 'alternate1';
			$pString .= TABLE::trStart();
// write Coins <span> data
			$coinsString = $coins->coinsDisplay($row);
			$pString .= TABLE::td($coinsString . $bibStyle->process($row), $class);
			foreach($links as $link)
				$pString .= TABLE::td($link . "&nbsp;", $class, "right", "top");
			if($multiUser)
				$pString .= TABLE::td(MISC::span($maturityIndex . $popularityIndex, 'hint'), 
					$class, "right", "top");
			$pString .= TABLE::td($checkBox, $class, "right", "top");
			$pString .= TABLE::trEnd();
			$index++;
		}
		$pString .= TABLE::tableEnd();
		if($form)
			$pString .= FORM::formEnd();
		$pagingString = $paging->links($queryString);
// set the lastMulti session variable for quick return to this process.
		$this->session->setVar('sql_lastMulti', $listType);
		return array($pString, $pagingString);
	}
		
	
/*
* listAttachments() - list only attachments
* 
* @author Mark Grimshaw
* 
* @param string $sqlTotal - SQL select statement to grab all resources required.
* @param string $queryString - URL query string such as "action=listProcess"
* @param string $listTYpe - What type of list/search/select process is this being called from?
* @param array $patterns - optional array of search terms to be matched and highlighted in bibstyle->process()
* @param string $message - optional message printed first
* @return string $pString
*/
	function listAttachments($sqlTotal, $queryString, $listType, $patterns, $message)
	{
// write statement to session in case we need to export to RTF etc.
		$this->session->setVar('sql_stmt', addslashes($sqlTotal));
		$this->session->setVar("sql_lastView", 'multi');
// set the lastMulti session variable for quick return to this process.
		$this->session->setVar('sql_lastMulti', $listType);
// Are only logged on users allowed to view this file and is this user logged on?
		if($this->session->getVar("setup_fileViewLoggedOnOnly") && !$this->session->getVar("setup_userId"))
			return array($this->messages->text('resources', 'noResult'), FALSE);
		include_once("core/paging/PAGING.php");
		$paging = new PAGING($this->db, $this->vars, $sqlTotal);
		include_once("core/html/TABLE.php");
		include_once("core/attachments/ATTACHMENTS.php");
		$attachments = new ATTACHMENTS($this->db, $this->vars);
		$pString = '';
		$recordset = $this->db->query($sqlTotal);
		$ids = array();
		while($row = $this->db->loopRecordSet($recordset))
			$ids[] = $row['resourceId'];
		if(empty($ids))
			return array($this->messages->text('resources', 'noResult'), FALSE);
// Zip files up?
		if($this->session->getVar($listType . '_displayAttachmentZip'))
		{
			if(file_exists("/usr/bin/gzip") && file_exists("/bin/tar"))
			{
				$path = "files/" . session_id() . "/";
				$zipPath = $path . 'zip/';
				$files = $attachments->attachedFileNames($ids, TRUE);
				if(!empty($files))
				{
					if(!@opendir($path))
					{
						if(!@mkdir($path))
						{
							include_once("core/html/CLOSE.php");
							new CLOSE($this->db, $this->errors->text('file', 'folder'));
						}
					}
					if(!@opendir($zipPath))
					{
						if(!@mkdir($zipPath))
						{
							include_once("core/html/CLOSE.php");
							new CLOSE($this->db, $this->errors->text('file', 'folder'));
						}
					}
					foreach($files as $hash => $fileName)
						@copy('attachments/' . $hash, $zipPath . $fileName);
					$tarFile = "files/" . session_id() . ".tar";
					exec("/bin/tar -cf $tarFile $zipPath");
					$zipFile = "files/" . session_id() . ".tar.gz";
					@unlink($zipFile);
					exec("/usr/bin/gzip -9 $tarFile");
					@unlink($tarFile); // to be safe
					foreach($files as $fileName)
						@unlink($zipPath . $fileName);
					@rmdir($zipPath);
					@rmdir($path);
					$zipFile = MISC::a('link', $zipFile, htmlentities($zipFile), "_new");
// Add file to session
					include_once("core/file/export/EXPORTCOMMON.php");
					$export = new EXPORTCOMMON($this->db);
					$export->writeFilenameToSession(session_id() . ".tar.gz");
					return array($zipFile, FALSE);
				}
				else
					@unlink("files/" . session_id() . ".tar.gz");
			}
		}
		$files = $attachments->attachedFileNames($ids);
		if(empty($files))
			return array($this->messages->text('resources', 'noResult'), FALSE);
		$paging->total = sizeof($files);
// Get slice of array according to paging
		$files = array_slice($files, $paging->start, $paging->paging);
		foreach($files as $file)
		{
			$pString .= TABLE::trStart();
			$pString .= TABLE::td($file);
			$pString .= TABLE::trEnd();
		}
		$pagingString = $paging->links($queryString);
		return array($pString, $pagingString);
	}
// Display list information and userBib, category and keyword select box to add items to
	function displaySelect($pagingObject, $listType)
	{
		include_once("core/resource/RESOURCE.php");
		$resource = new RESOURCE($this->db, $this->vars);
		include_once("core/messages/MESSAGES.php");
		$messages = new MESSAGES();
		$usingBib = FALSE;
		$bibs = array();
		if($this->session->getVar('mywikindx_bibliographies'))
			$bibs = unserialize($this->session->getVar("mywikindx_bibliographies"));
		if($this->session->getVar('mywikindx_groupbibliographies'))
			$bibs = array_merge($bibs, unserialize($this->session->getVar("mywikindx_groupbibliographies")));
		$useBib = $this->session->getVar('mywikindx_bibliography_use');
		if($useBib)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('title', 'userId'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($useBib));
			$row = $this->db->fetchRow($recordset);
			$usingBib = stripslashes($row['title']);
			$bibUserId = $row['userId'];
			if(array_key_exists($useBib, $bibs))
			{
				$usingBib = $bibs[$useBib];
				unset($bibs[$useBib]);
			}
		}
		include_once("core/group/GROUP.php");
		$group = new GROUP($this->db);
		$categories = $group->grabAll();
		include_once("core/keyword/KEYWORD.php");
		$keyword = new KEYWORD($this->db);
		$keywords = $keyword->grabAll();
		if(!empty($bibs))
			$array[0] = $messages->text("resources", "addToBib");
		if($this->session->getVar('setup_write'))
		{
			if(sizeof($categories) > 1)
				$array[1] = $messages->text("resources", "addToCategory");
			if($keywords)
				$array[2] = $messages->text("resources", "addToKeyword");
		}
		if(isset($bibUserId) && ($this->session->getVar('setup_userId') == $bibUserId))
			$array[3] = $messages->text('resources', 'deleteFromBib');
		else if($this->session->getVar("resourceSelectedTo") == '3') // previously operation was 'deleteFromBib'
			$this->session->delVar("resourceSelectedTo");
		if($this->session->getVar('setup_superadmin'))
			$array[4] = $messages->text('resources', 'deleteResource');
//		if(!isset($array) || !$pagingObject->total)
//			return array(MISC::p($pagingObject->linksInfo($usingBib)), FALSE);
		$pString = TABLE::tableStart();
		$pString .= TABLE::trStart();
		if($usingBib)
			$linksInfo = $pagingObject->linksInfo($usingBib);
		else
			$linksInfo = $pagingObject->linksInfo();
		$params = $this->listParams($listType);
		$pString .= TABLE::td($linksInfo . $params);

		if(!isset($array) || !$pagingObject->total)
		{
			$pString .= TABLE::trEnd() . TABLE::tableEnd();
			return array($pString, FALSE);
		}
		if($listType == 'list')
			$pString .= TABLE::td(FORM::formHeader("listReorder") . $this->displayAscDesc($listType) . 
				MISC::br() . FORM::formSubmit("List") . FORM::formEnd(), FALSE, FALSE, 'bottom');
		else if($listType == 'select')
			$pString .= TABLE::td(FORM::formHeader("selectReorder") . $this->displayOrder($listType, TRUE) . 
				MISC::br() . FORM::formSubmit("Select") . FORM::formEnd(), FALSE, FALSE, 'bottom');
		else if($listType == 'statistics')
			$pString .= TABLE::td(FORM::formHeader("statisticsReorder") . $this->displayOrder('select', TRUE) . 
				MISC::br() . FORM::formSubmit("Select") . FORM::formEnd(), FALSE, FALSE, 'bottom');
		else if($listType == 'search')
			$pString .= TABLE::td(FORM::formHeader("searchReorder") . $this->displayOrder($listType, TRUE) . 
				MISC::br() . FORM::formSubmit("Search") . FORM::formEnd(), FALSE, FALSE, 'bottom');
		$pString .= FORM::formHeader("selectedResourceTo");
		$pString .= FORM::hidden("method", "add");
		$sessVar = $this->session->getVar("resourceSelectedTo");
		$checkAll = $messages->text("resources", "selectAll") . ":&nbsp;&nbsp;" . 
			FORM::checkbox(FALSE, "selectAll");
		if($sessVar !== FALSE)
			$pString .= TABLE::td(FORM::selectedBoxValue($messages->text("resources",
				"withChecked"), "resourceSelectedTo", $array, $sessVar, sizeof($array)) . MISC::br() . 
				$checkAll . "&nbsp;&nbsp;" . 
				FORM::formSubmit("Proceed") . MISC::br() . "&nbsp;" . MISC::br(), FALSE, "right");
		else
			$pString .= TABLE::td(FORM::selectFBoxValue($messages->text("resources",
				"withChecked"), "resourceSelectedTo", $array, sizeof($array)) . MISC::br() . 
				$checkAll . "&nbsp;&nbsp;" . 
				FORM::formSubmit("Proceed") . MISC::br() . "&nbsp;" . MISC::br(), FALSE, "right");
		$pString .= TABLE::trEnd() . TABLE::tableEnd();
		return array($pString, TRUE);
	}
// Display some information about the search/select/list parameters
	function listParams($listType)
	{
		include_once('core/html/HTML.php');
		$html = new HTML();
		$strings = array();
		$pString = TABLE::tableStart();
		$pString .= TABLE::trStart();
		$pString .= MISC::br() . '&nbsp;' . MISC::br();
		$pString .= TABLE::td(MISC::span(MISC::b($this->messages->text('listParams', 'listParams')), 'hint'));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::trStart();
// Bookmarked multi view?
		if($this->session->getVar('bookmark_multiView'))
		{
			$strings = unserialize(base64_decode($this->session->getVar('sql_listParams')));
			if(empty($strings))
				return FALSE;
			$pString .= TABLE::td(join(MISC::br(), $strings));
			$pString .= TABLE::trEnd() . TABLE::tableEnd();
			$this->session->delVar('bookmark_multiView');
			return $pString;
		}
		if(array_key_exists('statistics', $this->vars) && ($this->vars['statistics'] == 'type'))
			$strings[] = MISC::span($this->messages->text('listParams', 'type') . ':&nbsp;&nbsp;' . 
				$this->vars['id'], 'hint');
		else if($id = $this->session->getVar($listType . "_type"))
		{
			$ids = explode(',', $id);
			if(sizeof($ids) > 1)
				$strings[] = MISC::span($this->messages->text('listParams', 'type') . ':&nbsp;&nbsp;' . 
					MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
			else
				$strings[] = MISC::span($this->messages->text('listParams', 'type') . ':&nbsp;&nbsp;' . 
					$id, 'hint');
		}
		if($listType == 'select')
		{
			if($id = $this->session->getVar($listType . '_tag'))
			{
				$ids = explode(',', $id);
				if(sizeof($ids) > 1)
					$strings[] = MISC::span($this->messages->text('listParams', 'tag') . ':&nbsp;&nbsp;' . 
						MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
				else
				{
					$resultSet = $this->db->select(array('WKX_tag'), 'tag', ' WHERE ' . 
						$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
					$strings[] = MISC::span($this->messages->text('listParams', 'tag') . ':&nbsp;&nbsp;' . 
						$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
				}
			}
			if($id = $this->session->getVar($listType . "_attachment"))
				$strings[] = MISC::span($this->messages->text('listParams', 'attachment'), 'hint');
		}
		if(($listType == 'listCategory') || ($id = $this->session->getVar($listType . '_category')))
		{
			if($listType == 'listCategory')
				$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
			$cats = explode(',', $id);
			if(sizeof($cats) > 1)
				$strings[] = MISC::span($this->messages->text('listParams', 'category') . ':&nbsp;&nbsp;' . 
					MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
			else
			{
				$resultSet = $this->db->select(array('WKX_category'), 'category', ' WHERE ' . 
					$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
				$strings[] = MISC::span($this->messages->text('listParams', 'category') . ':&nbsp;&nbsp;' . 
					$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
			}
		}
		if(($listType == 'listCollection') || ($id = $this->session->getVar($listType . '_collection')))
		{
			if($listType == 'listCollection')
				$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
			$cats = explode(',', $id);
			if(sizeof($cats) > 1)
				$strings[] = MISC::span($this->messages->text('listParams', 'collection') . ':&nbsp;&nbsp;' . 
					MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
			else
			{
				$resultSet = $this->db->select(array('WKX_collection'), 'collectionTitle', ' WHERE ' . 
					$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
				$strings[] = MISC::span($this->messages->text('listParams', 'collection') . ':&nbsp;&nbsp;' . 
					$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
			}
		}
		if(($listType == 'listPublisher') || ($id = $this->session->getVar($listType . '_publisher')))
		{
			if($listType == 'listPublisher')
				$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
			$cats = explode(',', $id);
			if(sizeof($cats) > 1)
				$strings[] = MISC::span($this->messages->text('listParams', 'publisher') . ':&nbsp;&nbsp;' . 
					MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
			else
			{
				$resultSet = $this->db->select(array('WKX_publisher'), array('publisherName', 
					'publisherLocation'), ' WHERE ' . 
					$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
				$row = $this->db->fetchRow($resultSet);
				if($row['publisherLocation'])
					$loc = ' (' . stripslashes($row['publisherLocation']) . ')';
				else
					$loc = FALSE;
				$publisher = stripslashes($row['publisherName']) . $loc;
				$strings[] = MISC::span($this->messages->text('listParams', 'publisher') . ':&nbsp;&nbsp;' . 
					$html->dbToHtmlTidy($publisher), 'hint');
			}
		}
		if(($listType == 'listKeyword') || ($id = $this->session->getVar($listType . '_keyword')))
		{
			if($listType == 'listKeyword')
				$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
			$ids = explode(',', $id);
			if(sizeof($ids) > 1)
				$strings[] = MISC::span($this->messages->text('listParams', 'keyword') . ':&nbsp;&nbsp;' . 
					MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
			else
			{
				$resultSet = $this->db->select(array('WKX_keyword'), 'keyword', ' WHERE ' . 
					$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
				$strings[] = MISC::span($this->messages->text('listParams', 'keyword') . ':&nbsp;&nbsp;' . 
					$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
			}
		}
		if(($listType == 'listCreator') || ($listType == 'select'))
		{
			if($id = $this->session->getVar($listType . '_bibId'))
			{
				$resultSet = $this->db->select(array('WKX_user_bibliography'), array('title'), 
					" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($id));
				$strings[] = MISC::span($this->messages->text('listParams', 'notInUserBib') . ':&nbsp;&nbsp;' . 
					$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
			}
			if(($listType == 'listCreator') || ($id = $this->session->getVar($listType . '_creator')))
			{
				if($listType == 'listCreator')
					$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
				$ids = explode(',', $id);
				if(sizeof($ids) > 1)
					$strings[] = MISC::span($this->messages->text('listParams', 'creator') . ':&nbsp;&nbsp;' . 
						MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
				else
				{
					$resultSet = $this->db->select(array('WKX_creator'), array('prefix', 'surname'), ' WHERE ' . 
						$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
					
					$row = $this->db->fetchRow($resultSet);
					$name = $row['prefix'] ? $row['prefix'] . ' ' . $row['surname'] : $row['surname'];
					$strings[] = MISC::span($this->messages->text('listParams', 'creator') . ':&nbsp;&nbsp;' . 
						$html->dbToHtmlTidy($name), 'hint');
						
					// requete pour afficher les institutions
					$resultSet2 = $this->db->select(array('WKX_creator_institution'), array('WKX_institution.name','WKX_institution.acronym','WKX_institution.id'),
					'LEFT JOIN' . $this->db->formatTable('WKX_institution') . " ON " . 
					$this->db->formatField('WKX_creator_institution.institution1') . "=" . $this->db->formatfield("WKX_institution.id"). "OR " . 
					$this->db->formatField('WKX_creator_institution.institution2') . "=" . $this->db->formatfield("WKX_institution.id"). "OR " . 
					$this->db->formatField('WKX_creator_institution.institution3') . "=" . $this->db->formatfield("WKX_institution.id")."OR " . 
					$this->db->formatField('WKX_creator_institution.institution4') . "=" . $this->db->formatfield("WKX_institution.id")."OR " . 
					$this->db->formatField('WKX_creator_institution.institution5') . "=" . $this->db->formatfield("WKX_institution.id").
					' WHERE ' . $this->db->formatField('WKX_creator_institution.id') . '=' . $this->db->tidyInput($id) );

					$total = array();
					$idLien = array();
					while($row2 = $this->db->loopRecordSet($resultSet2))
					{
						$name2 = $row2['acronym'] ? $row2['acronym'] . ' ' . $row2['name'] : $row2['name'];
						$id2 = $row2['id'];
						array_push($total,$name2);
						array_push($idLien,$id2);
					}
					$strings[] = MISC::span($this->messages->text('listParams', 'institution') . ':&nbsp;&nbsp;' . 
						MISC::aBrowse($colour, $size, $total[0], "index.php?action=browseCreator2" . 
							htmlentities("&id=" . $idLien[0])). '&nbsp;&nbsp;' . 
						MISC::aBrowse($colour, $size, $total[1], "index.php?action=browseCreator2" . 
							htmlentities("&id=" . $idLien[1])). '&nbsp;&nbsp;' . 
						MISC::aBrowse($colour, $size, $total[2], "index.php?action=browseCreator2" . 
							htmlentities("&id=" . $idLien[2])). '&nbsp;&nbsp;' . 
						MISC::aBrowse($colour, $size, $total[3], "index.php?action=browseCreator2" . 
							htmlentities("&id=" . $idLien[3])). '&nbsp;&nbsp;' . 
						MISC::aBrowse($colour, $size, $total[4], "index.php?action=browseCreator2" . 
							htmlentities("&id=" . $idLien[4])), 'hint');				
			
					// $strings[] = MISC::span($this->messages->text('listParams', 'institution') . ':&nbsp;&nbsp;' . 
						 // $html->dbToHtmlTidy($name2), 'hint');
				}
			}
/*			if(($listType == 'listPublisher') || ($id = $this->session->getVar($listType . '_publisher')))
			{
				if($listType == 'listPublisher')
					$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
				$ids = explode(',', $id);
				if(sizeof($ids) > 1)
					$strings[] = MISC::span($this->messages->text('listParams', 'publisher') . ':&nbsp;&nbsp;' . 
						MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
				else
				{
					$resultSet = $this->db->select(array('WKX_publisher'), array('publisherName', 
						'publisherLocation'), ' WHERE ' . 
						$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
					$row = $this->db->fetchRow($resultSet);
					if($row['publisherLocation'])
						$loc = ' (' . stripslashes($row['publisherLocation']) . ')';
					else
						$loc = FALSE;
					$publisher = stripslashes($row['publisherName']) . $loc;
					$strings[] = MISC::span($this->messages->text('listParams', 'publisher') . ':&nbsp;&nbsp;' . 
						$html->dbToHtmlTidy($publisher), 'hint');
				}
			}
			if(($listType == 'listCollection') || ($id = $this->session->getVar($listType . '_collection')))
			{
				if($listType == 'listCollection')
					$id = array_key_exists("id", $this->vars) ? 
					$this->vars["id"] : $this->session->getVar("list_ids");
				$ids = explode(',', $id);
				if(sizeof($ids) > 1)
					$strings[] = MISC::span($this->messages->text('listParams', 'collection') . 
						':&nbsp;&nbsp;' . 
						MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
				else
				{
					$resultSet = $this->db->select(array('WKX_collection'), 'collectionTitle', ' WHERE ' . 
						$this->db->formatField('id') . '=' . $this->db->tidyInput($id));
					$strings[] = MISC::span($this->messages->text('listParams', 'collection') . 
						':&nbsp;&nbsp;' . 
						$html->dbToHtmlTidy($this->db->fetchOne($resultSet)), 'hint');
				}
			}
*/
		}
		if($listType == 'search')
		{
			if($id = $this->session->getVar($listType . '_field'))
			{
				$ids = explode(',', $id);
				if(sizeof($ids) > 1)
					$strings[] = MISC::span($this->messages->text('listParams', 'field') . 
						':&nbsp;&nbsp;' . 
						MISC::i($this->messages->text('listParams', 'listParamMultiple')), 'hint');
				else
					$strings[] = MISC::span($this->messages->text('listParams', 'field') . 
						':&nbsp;&nbsp;' . $id, 'hint');
			}
			if($id = $this->session->getVar($listType . '_word'))
			{
				if($this->session->getVar($listType . '_method') == 'OR')
					$id = str_replace(' ', ' OR ', $id);
				else if($this->session->getVar($listType . '_method') == 'AND')
					$id = str_replace(' ', ' AND ', $id);
				else
					$id = "\"$id\"";
				if($this->session->getVar($listType . '_partial') == 'on')
					$id .= "&nbsp;(" . $this->messages->text('listParams', 'partial') . ")";
				$strings[] = MISC::span($this->messages->text('listParams', 'word') . 
					':&nbsp;&nbsp;' . $id, 'hint');
			}
		}
		if(empty($strings))
		{
			$this->session->delVar('sql_listParams');
			return FALSE;
		}
		$this->session->setVar('sql_listParams', base64_encode(serialize($strings)));
		$pString .= TABLE::td(join(MISC::br(), $strings));
		$pString .= TABLE::trEnd() . TABLE::tableEnd();
		return $pString;
	}
// Parse ordering input and create SQL condition fragment
	function parseOrder($input)
	{
		if($input['order'] == 'creator')
		{
			return " ORDER BY " . $this->db->tidyInputClause('surname') . 
				" " . $input['ascDesc'] . ", " . 
				$this->db->formatField('firstname') . ", " . 
				" COALESCE(" . $this->db->formatField('year1') . 
				", " . $this->db->formatField('year2') . 
				", " . $this->db->formatField('year3') . ")";
		}
		else if($input['order'] == 'title')
		{
			return " ORDER BY " . $this->db->tidyInputClause('title') . 
				" " . $input['ascDesc'] . ", " . 
				" COALESCE(" . $this->db->formatField('year1') . 
				", " . $this->db->formatField('year2') . 
				", " . $this->db->formatField('year3') . ")";
		}
		else if($input['order'] == 'timestamp')
		{
			return " ORDER BY " . $this->db->tidyInputClause('timestamp') . 
				" " . $input['ascDesc'] . ", " . 
				" COALESCE(" . $this->db->formatField('year1') . 
				", " . $this->db->formatField('year2') . 
				", " . $this->db->formatField('year3') . ")";
		}
		else if($input['order'] == 'publisher')
		{
			return " ORDER BY " . $this->db->tidyInputClause('publisherName') . 
				" " . $input['ascDesc'] . ", " . 
				" COALESCE(" . $this->db->formatField('year1') . 
				", " . $this->db->formatField('year2') . 
				", " . $this->db->formatField('year3') . ")";
		}
		else if($input['order'] == 'year')
		{
			return " ORDER BY " . 
				" COALESCE(" . $this->db->formatField('year1') . 
				", " . $this->db->formatField('year2') . 
				", " . $this->db->formatField('year3') . ")" . 
				" " . $input['ascDesc'];
		}
	}
// Ordering options for select and quicksearch
	function displayOrder($type, $reorder = FALSE)
	{
		include_once("core/messages/MESSAGES.php");
		$messages = new MESSAGES();
		$order = array(
					"creator" => $messages->text("list", "creator"),
					"title" => $messages->text("list", "title"),
					"publisher" => $messages->text("list", "publisher"),
					"year" => $messages->text("list", "year"),
					"timestamp" => $messages->text("list", "timestamp"),
				);
		$pString = '';
		if(!$reorder)
			$size = '5';
		else
			$size = '2';
		if($selected = $this->session->getVar($type . "_order"))
			$pString .= FORM::selectedBoxValue(
				$messages->text("list", "order"), $type . "_order", $order, $selected, $size);
		else
			$pString .= FORM::selectFBoxValue(
				$messages->text("list", "order"), $type . "_order", $order, $size);
		if(!$reorder)
			$pString .= MISC::p($this->displayAscDesc($type));
		else
		$pString .= MISC::br() . $this->displayAscDesc($type);
		return $pString;
	}
// Print radio buttons ascending, descending for ordering
	function displayAscDesc($type)
	{
		include_once("core/messages/MESSAGES.php");
		$messages = new MESSAGES();
		if($ascDesc = $this->session->getVar($type . "_ascDesc"))
		{
			if($ascDesc == 'ASC')
			{
				return FORM::radioButton(FALSE, $type . "_ascDesc", 'ASC', TRUE) . 
					$messages->text("powerSearch", "ascending") . 
					MISC::br() . FORM::radioButton(FALSE, $type . "_ascDesc", 'DESC') . 
					$messages->text("powerSearch", "descending");
			}
			else
			{
				return FORM::radioButton(FALSE, $type . "_ascDesc", 'ASC') . 
					$messages->text("powerSearch", "ascending") . 
					MISC::br() . FORM::radioButton(FALSE, $type . "_ascDesc", 'DESC', TRUE) . 
					$messages->text("powerSearch", "descending");
			}
		}
		else
		{
			return FORM::radioButton(FALSE, $type . "_ascDesc", 'ASC', TRUE) . 
				$messages->text("powerSearch", "ascending") . 
				MISC::br() . FORM::radioButton(FALSE, $type . "_ascDesc", 'DESC') . 
				$messages->text("powerSearch", "descending");
		}
	}
}
?>
